// src/Setting.tsx
import React, { type CSSProperties, useState, useEffect } from 'react';
import {
  LogoutOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { Card, List, Button, message } from 'antd';
import ChangePassword from './ChangePassword';
import ChangeUsername from './ChangeUsername';
import ChangeProfilePicture from './ChangeProfilePicture';

interface SettingItem {
  title: string;
  description: string;
  icon: React.ReactNode;
  action: React.ReactNode;
  onClick: () => void;
}

interface UserInfo {
  id: number;
  username: string;
  nickname: string;
  avatar?: string;
}

interface SettingProps {
  onUserUpdate?: () => void;
}

interface UploadState {
  isUploading: boolean;
  lastUploadTime: number;
}


const SettingContent: React.FC<SettingProps> = ({ onUserUpdate }) => {
  const [userInfo, setUserInfo] = useState<UserInfo>({
    id: 0,
    username: '',
    nickname: '',
    avatar: ''
  });

  const [modals, setModals] = useState({
    username: false,
    password: false,
  });

  const [loading, setLoading] = useState({
    avatar: false
  });

  // 上传状态管理
  const [uploadState, setUploadState] = useState<UploadState>({
    isUploading: false,
    lastUploadTime: 0
  });

  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        const userId = localStorage.getItem('userId');

        if (!token || !userId) {
          message.warning('请先登录');
          return;
        }

        const storedUserInfo = localStorage.getItem('userInfo');
        if (storedUserInfo) {
          try {
            const userData = JSON.parse(storedUserInfo);
            if (userData.avatarBase64) {
              setUserInfo({
                id: userData.id,
                username: userData.username,
                nickname: userData.nickname || userData.username,
                avatar: userData.avatarBase64
              });
              return;
            }
          } catch (e) {
            console.error('解析本地用户信息失败:', e);
          }
        }

        const response = await fetch(`/api/users/${userId}`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });

        if (response.ok) {
          const userData = await response.json();
          const updatedUserInfo = {
            id: userData.id,
            username: userData.username,
            nickname: userData.nickname || userData.username,
            avatar: userData.avatar ? `http://218.244.141.86:8080${userData.avatar}` : ''
          };
          setUserInfo(updatedUserInfo);
          localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    fetchUserInfo();
  }, []);

  const styles: { [key: string]: CSSProperties } = {
    container: {
      padding: '0',
      minHeight: '400px',
    },
    contentWrapper: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      width: '100%',
    },
    contentCard: {
      borderRadius: '8px',
      boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
      width: '100%',
      marginBottom: '16px',
    },
    listItem: {
      padding: '12px 16px',
      borderBottom: '1px solid #f0f0f0',
    },
    logoutSection: {
      width: '100%',
      textAlign: 'center',
      marginTop: '16px',
    },
    logoutBtn: {
      width: '100%',
      height: '40px',
      borderRadius: '6px',
      fontSize: '14px',
    },
    actionText: {
      color: '#1890ff',
      cursor: 'pointer',
      fontSize: '13px',
    }
  };

  const checkAuth = (): boolean => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    if (!token) {
      message.warning('请先登录');
      setTimeout(() => {
        window.location.href = '/login';
      }, 1000);
      return false;
    }
    return true;
  };

  const openModal = (modalName: keyof typeof modals) => {
    if (!checkAuth()) return;
    setModals(prev => ({ ...prev, [modalName]: true }));
  };

  const closeModal = (modalName: keyof typeof modals) => {
    setModals(prev => ({ ...prev, [modalName]: false }));
  };



  // 在 Setting.tsx 中修改 handleAvatarUpload 函数
const handleAvatarUpload = async (file: File) => {
  // 防抖和防重复上传
  const now = Date.now();
  const timeSinceLastUpload = now - uploadState.lastUploadTime;
  
  if (uploadState.isUploading) {
    message.warning('正在上传中，请稍候...');
    return;
  }
  
  if (timeSinceLastUpload < 2000) {
    message.warning('上传操作过于频繁，请等待2秒后重试');
    return;
  }

  // 更新上传状态
  setUploadState(prev => ({ ...prev, isUploading: true }));
  setLoading(prev => ({ ...prev, avatar: true }));

  try {
    const formData = new FormData();
    formData.append('file', file);

    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    const userId = localStorage.getItem('userId');

    if (!userId) {
      message.error('用户ID不存在，请重新登录');
      setUploadState(prev => ({ ...prev, isUploading: false }));
      return;
    }

    console.log('开始上传头像，时间戳:', now);

    // 添加超时控制
    const controller = new AbortController();
    const timeoutId = setTimeout(() => {
      controller.abort();
      console.log('上传超时，已取消请求');
    }, 30000);

    // 先读取为base64用于立即显示
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const base64 = e.target?.result as string;
        
        // 立即更新UI显示新头像
        const tempUserInfo = {
          ...userInfo,
          avatar: base64
        };
        setUserInfo(tempUserInfo);

        // 执行上传
        const response = await fetch(`/api/users/${userId}/avatar`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`
          },
          body: formData,
          signal: controller.signal
        });

        clearTimeout(timeoutId);

        console.log('头像上传响应状态:', response.status);

        if (response.ok) {
          let result;
          const contentType = response.headers.get('content-type');
          
          if (contentType && contentType.includes('application/json')) {
            result = await response.json();
          } else {
            result = await response.text();
          }
          
          console.log('头像上传成功，服务器返回:', result);

          // 更新本地存储
          const updatedUserInfo = {
            ...userInfo,
            avatar: base64 // 保持使用base64，避免URL缓存问题
          };
          
          setUserInfo(updatedUserInfo);
          
          const userDataWithAvatar = {
            ...updatedUserInfo,
            avatarBase64: base64,
            avatarLastUpdated: now
          };
          localStorage.setItem('userInfo', JSON.stringify(userDataWithAvatar));
          
          message.success('头像上传成功');
          
          if (onUserUpdate) {
            onUserUpdate();
          }

        } else {
          let errorMsg = '头像上传失败';
          try {
            const errorData = await response.json();
            errorMsg = errorData.message || errorData.error || `HTTP ${response.status}`;
          } catch (e) {
            try {
              const text = await response.text();
              errorMsg = text || `HTTP ${response.status}`;
            } catch (textError) {
              errorMsg = `HTTP ${response.status} ${response.statusText}`;
            }
          }
          console.error('头像上传错误详情:', errorMsg);
          
          // 上传失败时恢复原头像
          const storedUserInfo = localStorage.getItem('userInfo');
          if (storedUserInfo) {
            try {
              const originalUserInfo = JSON.parse(storedUserInfo);
              setUserInfo(originalUserInfo);
            } catch (parseError) {
              console.error('恢复原头像失败:', parseError);
            }
          }
          
          throw new Error(errorMsg);
        }
      } catch (error) {
        console.error('上传处理失败:', error);
        throw error;
      }
    };

    reader.onerror = () => {
      console.error('文件读取失败');
      message.error('文件读取失败，请重试');
      setUploadState(prev => ({ ...prev, isUploading: false }));
      setLoading(prev => ({ ...prev, avatar: false }));
    };
    
    reader.readAsDataURL(file);

  } catch (error) {
    console.error('上传头像失败:', error);
    
    if (error instanceof Error) {
      if (error.name === 'AbortError') {
        message.error('上传超时，请检查网络连接后重试');
      } else {
        message.error(`头像上传失败: ${error.message}`);
      }
    } else {
      message.error('头像上传失败，请稍后重试');
    }
  } finally {
    setUploadState(prev => ({ ...prev, isUploading: false }));
    setLoading(prev => ({ ...prev, avatar: false }));
  }
};

  const handleUsernameSuccess = (newUsername: string) => {
    const updatedUserInfo = {
      ...userInfo,
      username: newUsername
    };
    
    setUserInfo(updatedUserInfo);
    localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));
    
    if (onUserUpdate) {
      onUserUpdate();
    }

    setTimeout(() => {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('userId');
      sessionStorage.removeItem('token');
      window.location.href = '/login';
    }, 1500);
  };

  const handleLogout = () => {
    const confirmed = window.confirm('您确定要退出登录吗？');
    if (confirmed) {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('userId');
      sessionStorage.removeItem('token');
      
      message.success('已退出登录');
      
      setTimeout(() => {
        window.location.href = '/login';
      }, 500);
    }
  };

  const settingsData: SettingItem[] = [
    {
      title: '更改用户名',
      description: '修改您的登录用户名',
      icon: <EditOutlined />,
      action: <span style={styles.actionText}>修改</span>,
      onClick: () => openModal('username'),
    },
    {
      title: '更改密码',
      description: '定期更改密码保护账户安全',
      icon: <EditOutlined />,
      action: <span style={styles.actionText}>修改</span>,
      onClick: () => openModal('password'),
    },
  ];

  return (
    <div style={styles.container}>
      <div style={styles.contentWrapper}>
        <ChangeProfilePicture
          userInfo={userInfo}
          loading={loading.avatar || uploadState.isUploading}
          onUpload={handleAvatarUpload}
          onUserUpdate={onUserUpdate}
        />

        <Card style={styles.contentCard} bodyStyle={{ padding: 0 }}>
          <List
            dataSource={settingsData}
            renderItem={(item) => (
              <List.Item
                style={styles.listItem}
                actions={[item.action]}
                onClick={item.onClick}
              >
                <List.Item.Meta
                  avatar={item.icon}
                  title={<span style={{ fontSize: '14px' }}>{item.title}</span>}
                  description={<span style={{ fontSize: '12px' }}>{item.description}</span>}
                />
              </List.Item>
            )}
          />
        </Card>

        <div style={styles.logoutSection}>
          <Button
            type="primary"
            danger
            icon={<LogoutOutlined />}
            onClick={handleLogout}
            style={styles.logoutBtn}
          >
            退出登录
          </Button>
        </div>
      </div>

      <ChangeUsername
        visible={modals.username}
        onClose={() => closeModal('username')}
        currentUsername={userInfo.username}
        onSuccess={handleUsernameSuccess}
      />

      <ChangePassword
        visible={modals.password}
        onClose={() => closeModal('password')}
        username={userInfo.username}
      />
    </div>
  );
};

export default SettingContent;